<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<navigation-bar title="排行榜" :back="true" @back="onBackTap"></navigation-bar>
		
		<!-- 页面内容区域 -->
		<view class="content-wrapper">
			<!-- 标签栏 -->
			<view class="tabs-section">
				<view class="tabs-container">
					<view 
						v-for="(tab, index) in tabs" 
						:key="index"
						class="tab-item"
						:class="{ active: currentTab === index }"
						:data-index="index"
						@tap="onTabChange"
					>
						<text class="tab-text">{{ tab }}</text>
						<view class="tab-indicator" v-if="currentTab === index"></view>
					</view>
				</view>
			</view>

			<!-- 我的排名卡片 -->
			<view class="my-ranking-card">
				<view class="card-header">
					<text class="card-title">我的排名</text>
					<view class="rank-info">
						<text class="rank-number">第{{ myRanking.rank }}名</text>
					</view>
				</view>
				<view class="card-content">
					<view class="user-section">
						<image class="user-avatar" :src="myRanking.avatar"></image>
						<view class="user-details">
							<text class="user-name">{{ myRanking.name }}</text>
							<text class="user-score">{{ myRanking.score }}{{ getScoreUnit() }}</text>
						</view>
					</view>
					<view class="progress-section">
						<view class="progress-bar">
							<view class="progress-fill" :style="{ width: getProgressWidth() }"></view>
						</view>
						<text class="progress-text">学习进度</text>
					</view>
				</view>
			</view>

			<!-- 排行榜列表 -->
			<view class="ranking-section">
				<view class="section-header">
					<text class="section-title">排行榜</text>
					<text class="section-subtitle">共{{ rankingList.length }}人参与</text>
				</view>
				<scroll-view class="ranking-list" scroll-y>
					<!-- 加载状态 -->
					<view v-if="loading" class="loading-container">
						<text class="loading-text">加载中...</text>
					</view>
					<!-- 排行榜列表 -->
					<view 
						v-for="(item, index) in rankingList" 
						:key="index"
						class="ranking-item"
						:class="{ 
							'top-three': index < 3,
							'first': index === 0,
							'second': index === 1,
							'third': index === 2
						}"
						:data-id="item.userId"
						@tap="onUserTap"
					>
						<!-- 排名显示 -->
						<view class="rank-display">
							<view class="rank-number" :class="{ 'medal': item.badge }">
								<image v-if="item.badge" :src="getBadgeIcon(item.badge)" class="badge-icon"></image>
								<text v-else class="rank-text">{{ item.rank }}</text>
							</view>
						</view>
						
						<!-- 用户信息 -->
						<view class="user-info">
							<image class="user-avatar" :src="item.avatar"></image>
							<view class="user-details">
								<text class="user-name">{{ item.name }}</text>
								<text class="user-score">{{ item.score }}{{ getScoreUnit() }}</text>
							</view>
						</view>
						
						<!-- 排名标签 -->
						<view class="rank-badge">
							<text class="badge-text">{{ getRankText(item.rank) }}</text>
						</view>
					</view>
					<!-- 空状态 -->
					<view v-if="!loading && rankingList.length === 0" class="empty-container">
						<text class="empty-text">暂无排行榜数据</text>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 底部导航栏 -->
		<bottom-navigation current-page="ranking" @navigate="onNavigate"></bottom-navigation>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentTab: 0,
				tabs: ['学习时长', '小红花排行'],
				myRanking: {
					rank: 0,
					score: 0,
					avatar: '/static/avatar.png',
					name: '我的排名'
				},
				rankingList: [],
				loading: false,
				userExtraData: []
			}
		},
		onLoad: function (options) {
			console.log('排行榜页面加载');
			this.loadRankingData();
		},
		onShow: function () {
			console.log('排行榜页面显示');
			this.loadRankingData();
		},
		methods: {
			// 返回上一页
			onBackTap: function() {
				uni.navigateBack();
			},
			// 切换标签页
			onTabChange: function(e) {
				const index = e.currentTarget.dataset.index;
				this.currentTab = index;
				
				// 根据不同标签页加载不同数据
				this.loadRankingData();
			},
			// 加载排行榜数据
			loadRankingData: function() {
				if (this.loading) return;
				
				this.loading = true;
				console.log('加载排行榜数据，标签页:', this.currentTab);
				
				// 调用后端接口获取数据
				uni.request({
					url: 'http://localhost:1001/extra/findAll',
					method: 'GET',
					success: (res) => {
						console.log('获取用户数据成功:', res.data);
						this.userExtraData = res.data || [];
						this.processRankingData();
						this.loading = false;
					},
					fail: (err) => {
						console.error('获取用户数据失败:', err);
						uni.showToast({
							title: '数据加载失败',
							icon: 'none'
						});
						this.loading = false;
					}
				});
			},
			// 处理排行榜数据
			processRankingData: function() {
				if (!this.userExtraData || this.userExtraData.length === 0) {
					this.rankingList = [];
					return;
				}
				
				// 根据当前标签页排序数据
				let sortedData = [...this.userExtraData];
				if (this.currentTab === 0) {
					// 学习时长排序
					sortedData.sort((a, b) => (b.totalStudyTime || 0) - (a.totalStudyTime || 0));
				} else {
					// 小红花排序
					sortedData.sort((a, b) => (b.redFlower || 0) - (a.redFlower || 0));
				}
				
				// 转换为排行榜格式
				this.rankingList = sortedData.map((item, index) => {
					const score = this.currentTab === 0 ? (item.totalStudyTime || 0) : (item.redFlower || 0);
					return {
						rank: index + 1,
						name: item.nickname || '用户' + (index + 1),
						avatar: item.avatar || '/static/avatar.png',
						score: score,
						badge: index === 0 ? 'gold' : index === 1 ? 'silver' : index === 2 ? 'bronze' : null,
						userId: item.userId
					};
				});
				
				// 更新我的排名信息（这里假设当前用户是第一个，实际应该根据登录用户ID匹配）
				if (this.rankingList.length > 0) {
					const myData = this.userExtraData[0]; // 假设当前用户是第一个
					this.myRanking = {
						rank: this.rankingList.findIndex(item => item.userId === myData.userId) + 1 || this.rankingList.length + 1,
						score: this.currentTab === 0 ? (myData.totalStudyTime || 0) : (myData.redFlower || 0),
						avatar: myData.avatar || '/static/avatar.png',
						name: myData.nickname || '我的排名'
					};
				}
			},
			// 获取分数单位
			getScoreUnit: function() {
				const units = ['min', '朵'];
				return units[this.currentTab] || '';
			},
			// 获取徽章图标
			getBadgeIcon: function(badge) {
				const icons = {
					gold: '/static/medal-gold.svg',
					silver: '/static/medal-silver.svg',
					bronze: '/static/medal-bronze.svg'
				};
				return icons[badge] || '';
			},
			// 获取排名文本
			getRankText: function(rank) {
				if (rank <= 3) {
					return '优秀';
				} else if (rank <= 10) {
					return '良好';
				} else {
					return '加油';
				}
			},
			// 获取进度条宽度
			getProgressWidth: function() {
				if (this.rankingList.length === 0) return '0%';
				
				const maxScore = this.rankingList[0]?.score || 1;
				const currentScore = this.myRanking.score || 0;
				const percentage = Math.min((currentScore / maxScore) * 100, 100);
				return percentage + '%';
			},
			// 查看用户详情
			onUserTap: function(e) {
				const userId = e.currentTarget.dataset.id;
				console.log('查看用户详情:', userId);
				uni.showToast({
					title: '功能开发中',
					icon: 'none'
				});
			},
			// 全局导航栏事件处理
			onNavigate: function(e) {
				const page = e.detail.page;
				console.log('导航到页面:', page);
				// 导航逻辑已在组件内部处理
			}
		}
	}
</script>

<style>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
		position: relative;
		overflow: hidden;
	}

	.container::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
					radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.3) 0%, transparent 50%),
					radial-gradient(circle at 40% 40%, rgba(120, 219, 255, 0.2) 0%, transparent 50%);
		pointer-events: none;
	}

	.content-wrapper {
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		position: relative;
		z-index: 1;
	}

	/* 标签栏 */
	.tabs-section {
		background: transparent;
		border-bottom: none;
		box-shadow: none;
		margin-top: -20px;
		position: relative;
		z-index: 2;
	}

	.tabs-container {
		display: flex;
		padding: 0 20px;
	}

	.tab-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 16px 0;
		position: relative;
		transition: all 0.3s ease;
	}

	.tab-text {
		font-size: 16px;
		color: rgba(255, 255, 255, 0.8);
		font-weight: 500;
		transition: all 0.3s ease;
		margin-bottom: 8px;
		text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
	}

	.tab-item.active .tab-text {
		color: white;
		font-weight: 600;
		text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
	}

	.tab-indicator {
		width: 24px;
		height: 3px;
		background: linear-gradient(90deg, #ffffff, #f093fb);
		border-radius: 2px;
		animation: slideIn 0.3s ease;
		box-shadow: 0 2px 8px rgba(255, 255, 255, 0.5);
	}

	@keyframes slideIn {
		from { width: 0; }
		to { width: 24px; }
	}

	/* 我的排名卡片 */
	.my-ranking-card {
		margin: 12px 20px;
		background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(255, 255, 255, 0.8) 100%);
		backdrop-filter: blur(10px);
		border-radius: 16px;
		padding: 16px 20px;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
		border: 1px solid rgba(255, 255, 255, 0.3);
		position: relative;
		overflow: hidden;
	}

	.my-ranking-card::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(240, 147, 251, 0.1) 100%);
		pointer-events: none;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12px;
		position: relative;
		z-index: 2;
	}

	.card-title {
		font-size: 18px;
		font-weight: 600;
		color: #1f2937;
		text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
	}

	.rank-info {
		background: linear-gradient(135deg, #667eea, #f093fb);
		padding: 8px 16px;
		border-radius: 16px;
		box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
	}

	.rank-number {
		font-size: 14px;
		font-weight: 600;
		color: white;
	}

	.card-content {
		display: flex;
		flex-direction: row;
		align-items: center;
		gap: 20px;
		position: relative;
		z-index: 2;
	}

	.user-section {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.user-avatar {
		width: 50px;
		height: 50px;
		border-radius: 50%;
		border: 3px solid rgba(102, 126, 234, 0.3);
		box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
	}

	.user-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.user-name {
		font-size: 16px;
		font-weight: 600;
		color: #1f2937;
	}

	.user-score {
		font-size: 14px;
		color: #6b7280;
		font-weight: 500;
	}

	.progress-section {
		display: flex;
		flex-direction: column;
		gap: 6px;
		flex: 1;
	}

	.progress-bar {
		height: 6px;
		background: #f1f5f9;
		border-radius: 3px;
		overflow: hidden;
		position: relative;
	}

	.progress-fill {
		height: 100%;
		background: linear-gradient(90deg, #667eea, #f093fb);
		border-radius: 3px;
		transition: width 0.8s ease;
		box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
	}

	.progress-text {
		font-size: 12px;
		color: #6b7280;
		text-align: center;
	}

	/* 排行榜区域 */
	.ranking-section {
		flex: 1;
		margin: 0 10px 20px 10px;
		display: flex;
		flex-direction: column;
		min-height: 0;
		position: relative;
		z-index: 1;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12px;
	}

	.section-title {
		font-size: 18px;
		font-weight: 600;
		color: white;
		text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
	}

	.section-subtitle {
		font-size: 12px;
		color: rgba(255, 255, 255, 0.8);
		text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
	}

	.ranking-list {
		flex: 1;
		background: rgba(255, 255, 255, 0.95);
		backdrop-filter: blur(10px);
		border-radius: 16px;
		overflow: hidden;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
		border: 1px solid rgba(255, 255, 255, 0.3);
	}

	.ranking-item {
		display: flex;
		align-items: center;
		padding: 16px 20px;
		border-bottom: 1px solid #f8fafc;
		transition: all 0.2s ease;
		position: relative;
	}

	.ranking-item:last-child {
		border-bottom: none;
	}

	.ranking-item:active {
		background: #f8fafc;
		transform: scale(0.98);
	}

	.ranking-item.first {
		background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
		box-shadow: 0 4px 16px rgba(251, 191, 36, 0.3);
	}

	.ranking-item.second {
		background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
		box-shadow: 0 4px 16px rgba(107, 114, 128, 0.2);
	}

	.ranking-item.third {
		background: linear-gradient(135deg, #fed7aa 0%, #fdba74 100%);
		box-shadow: 0 4px 16px rgba(251, 146, 60, 0.3);
	}

	.rank-display {
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 16px;
	}

	.rank-number {
		width: 32px;
		height: 32px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background: #f8fafc;
		border: 2px solid #e2e8f0;
		transition: all 0.3s ease;
	}

	.rank-number.medal {
		background: linear-gradient(135deg, #fbbf24, #f59e0b);
		border-color: #f59e0b;
		box-shadow: 0 6px 20px rgba(251, 191, 36, 0.4);
		transform: scale(1.1);
	}

	.badge-icon {
		width: 20px;
		height: 20px;
	}

	.rank-text {
		font-size: 14px;
		font-weight: 700;
		color: #374151;
	}

	.rank-number.medal .rank-text {
		color: white;
	}

	.user-info {
		flex: 1;
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.user-avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		border: 2px solid #e2e8f0;
	}

	.user-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 2px;
	}

	.user-name {
		font-size: 14px;
		font-weight: 600;
		color: #1f2937;
	}

	.user-score {
		font-size: 12px;
		color: #6b7280;
		font-weight: 500;
	}

	.rank-badge {
		display: flex;
		align-items: center;
	}

	.badge-text {
		font-size: 10px;
		color: #059669;
		font-weight: 600;
		background: #d1fae5;
		padding: 4px 8px;
		border-radius: 8px;
		text-transform: uppercase;
		letter-spacing: 0.5px;
	}

	.ranking-item.first .badge-text {
		background: #fef3c7;
		color: #d97706;
	}

	.ranking-item.second .badge-text {
		background: #f3f4f6;
		color: #6b7280;
	}

	.ranking-item.third .badge-text {
		background: #fed7aa;
		color: #ea580c;
	}

	/* 加载状态 */
	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40px 20px;
	}

	.loading-text {
		font-size: 14px;
		color: #6b7280;
	}

	/* 空状态 */
	.empty-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 60px 20px;
	}

	.empty-text {
		font-size: 14px;
		color: #9ca3af;
	}
</style>


